from django.http import HttpResponseRedirect, HttpResponse, HttpResponseNotFound, HttpResponseNotAllowed
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from intr.models.models import *
from intr.events.models import *
from forms import EventForm
from django.core import serializers

def all_events(request, format=None):
	events = Event.objects.all().order_by('start')[:100]
	if format == 'json':
		data = serializers.serialize('json', events, fields=('name', 'lat', 'lon', 'description', 'location', 'society', 'start', 'end'))
		return HttpResponse(data, mimetype='application/json')
	return render_to_response('societies/events.html', {'events':events}, context_instance=RequestContext(request))


def user_events(request, format):
	user = request.user
	if request.GET.get('username'):
		user = User.objects.get(username=request.GET.get('username'))
	
	if not user or not user.is_authenticated():
		return HttpResponseNotFound()
	
	events = Event.objects.all().filter(society__in=[s for s in user.society_set.all()]).order_by('start')[:100]
	if format == 'json':
		data = serializers.serialize('json', events, fields=('name', 'lat', 'lon', 'description', 'location', 'society', 'start', 'end'))
		return HttpResponse(data, mimetype='application/json')
	else:
		return None


def create_event(request, slug):
	society = Society.objects.get(slug=slug)
	user = request.user
	
	if not society or not user.is_authenticated():
		return HttpResponseRedirect('/societies/%s/events' % society.slug)
	
	if request.POST:
		form = EventForm(request.POST, instance=None)
		if form.is_valid():
			form.save()
			return HttpResponseRedirect('/societies/%s/events' % society.slug)
	else:
		form = EventForm(instance=None)
	
	return render_to_response('events/edit.html', {'form':form, 'society':society}, context_instance=RequestContext(request))

